﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI.Controls
{
    
    public partial class RefundCtrl : BaseEditControl
    {
        const string WHOLESALE = "WHOLESALE";
        const string SALE = "RETAIL";
        const string PARTNER = "PARTNER";

        FinishSubmit onFinishSubmit;

        public FinishSubmit OnFinishSubmit
        {
            get { return onFinishSubmit; }
            set { onFinishSubmit = value; }
        }

        public bool IsSalePrice
        {
            get 
            {
                if (ViewState["IsSalePrice"] == null)
                    ViewState["IsSalePrice"] = true;
                return (bool)ViewState["IsSalePrice"];
            }
            set { ViewState["IsSalePrice"] = value; }
        }

        public string GetInvoiceDetailsEditPageLink()
        {
            return this.ResolveUrl("~/EditPages/EditInvoiceDetails.aspx") + "?key=" + invoiceDetails.SourceObjectSessionID;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (!IsPostBack)
            {
                InvoiceType invType = InvoiceType.GetAllActiveInvoiceType();
                Utilities.LoadDropDownListNoSelect(ddlInvoiceType, invType.DefaultView, InvoiceType.ColumnNames.InvoiceTypeName, InvoiceType.ColumnNames.ID);
                invType.Filter = InvoiceType.ColumnNames.Default + "=1";
                if (invType.RowCount > 0)
                    ddlInvoiceType.SelectedValue = invType.ID.ToString();

                lblStaff.Text = SessionUser.s_FullName;

                //Load for Combobox ACTK
                Customers cust = Customers.GetAllActiveCustomers();
                cust.Sort = Customers.ColumnNames.CustomerName + " asc";
                ddlCustomer.DataTextField = Customers.ColumnNames.CustomerName;
                ddlCustomer.DataValueField = Customers.ColumnNames.ID;
                ddlCustomer.DataSource = cust.DefaultView;
                ddlCustomer.DataBind();
                ListItem defaultCust = new ListItem("Cash Sales", "Sales");
                ddlCustomer.Items.Add(defaultCust);
                ddlCustomer.SelectedValue = defaultCust.Value;
                CustomerPrice = CustomerType.CustomerPrice.SalePrice;

                txtDate.Text = DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString(SysVars.DateFormat);

                PaymentMethod methods = PaymentMethod.GetAllMethods();
                Utilities.LoadDropDownList(ddlPaymentMethod, methods.DefaultView, PaymentMethod.ColumnNames.Name, PaymentMethod.ColumnNames.ID);
                //methods.Filter = PaymentMethod.ColumnNames.Default + "=1 and " + PaymentMethod.ColumnNames.MethodType + "='B'";
                //if (methods.RowCount > 0)
                //    ddlPaymentMethod.SelectedValue = methods.ID.ToString();

                NewInvoice();
            }
        }

        public bool ShowNewInvoice
        {
            get { return btnNewInvoice.Visible; }
            set { btnNewInvoice.Visible = value;}
        }

        public void NewInvoice()
        {
            Sequence seq = new Sequence();

            txtInvoiceNo.Text = seq.GetNewID("Invoices");
            invoiceDetails.TotalAmt = 0;
            invoiceDetails.TotalGST = 0;
            invoiceDetails.SaleItems = new InvoiceDetails();
            invoiceDetails.SaleItems.LoadByPrimaryKey(-1);
            txtPayAmt.Text = "0";
            txtNote.Text = "";
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            invoiceDetails.Refresh();

            RefreshCustPrice();
            btnSubmit.Visible = true;
            btnPrint.Visible = false;

            ddlPaymentMethod.SelectedIndex = 0;
        }

        protected void ddlCustomer_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshCustPrice();
            invoiceDetails.AdjustPrice(CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);
        }

        protected void btnEditProd_Click(Object sender, EventArgs e)
        {
            invoiceDetails.UpdateTotalAmt();
            invoiceDetails.Refresh();
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        protected void btnRemoveProd_Click(object sender, EventArgs e)
        {
            invoiceDetails.DeleteCheckedItems();
            invoiceDetails.UpdateTotalAmt();
            invoiceDetails.Refresh();
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        public int CustomerPrice
        {
            get
            {
                if (ViewState["CustomerPrice"] == null)
                    ViewState["CustomerPrice"] = CustomerType.CustomerPrice.SalePrice;
                return (int)ViewState["CustomerPrice"];
            }
            set { ViewState["CustomerPrice"] = value; }
        }


        private void RefreshCustPrice()
        {
            int custID;
            try
            {
                custID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                custID = -1;
            }

            View_Customers cust = View_Customers.GetCustomerByID(custID);
            CustomerPrice = cust.Price;
            //IsSalePrice = cust.RowCount <= 0 || cust.DealerPrice == false; //no longer used
            //lblCustPrice.Text = IsSalePrice ? SALE : WHOLESALE;//

            if (cust.Price == CustomerType.CustomerPrice.SalePrice)
            {
                lblCustPrice.Text = SALE;
            }
            else if (cust.Price == CustomerType.CustomerPrice.DealerPrice)
                lblCustPrice.Text = WHOLESALE;
            else if (cust.Price == CustomerType.CustomerPrice.PartnerPrice)
                lblCustPrice.Text = PARTNER;
        }

        protected void ddlCustomer_OnItemInserted(object sender, EventArgs e)
        {
            string cust = ddlCustomer.Text;
            lblCustPrice.Text = SALE;
        }

        public void AddIMEI(string imei)
        {
            invoiceDetails.AddIMEI(imei, CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
        }

        public void AddRefundIMEI(int modelID, string productName, string imei, decimal salePrice)
        {
            invoiceDetails.AddRefundIMEI(modelID, productName, imei, salePrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
        }

        public void AddProduct(int productID, int quantity)
        {
            invoiceDetails.AddNonIMEIProduct(productID, quantity, CustomerPrice);
            txtTotalAmt.Text = string.Format("{0:C}", invoiceDetails.TotalAmt);

            //update
            updateInvoice.Update();
            updateTotalAmtLabel.Update();
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            if (ddlCustomer.SelectedIndex < 0 || ddlCustomer.Text.Trim() == "")
            {
                ShowErrorMessage(mainPanel, "(*) Please select a customer!");
                return;
            }

            if (Invoices.IsInvoiceNoExisted(txtInvoiceNo.Text))
            {
                ShowErrorMessage(mainPanel, "(*) Invoice number has already existed!");
                return;
            }

            int customerID = 0;
            try
            {
                customerID = int.Parse(ddlCustomer.SelectedValue);
            }
            catch (Exception ex)
            {
                customerID = 0;
            }

            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();
                //step1:create invoice
                Invoices invoice = new Invoices();
                invoice.AddNew();
                invoice.BranchID = Branches.CurrentBranchID;
                invoice.SaleUser = SessionUser.ID;
                invoice.LastModifiedByUser = SessionUser.ID;
                invoice.CreatedByUser = SessionUser.ID;
                invoice.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                invoice.Note = txtNote.Text;
                invoice.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                invoice.PaidAmount = 0;
                invoice.CustomerName = ddlCustomer.SelectedItem.Text;
                invoice.TotalAmount = invoiceDetails.TotalAmt;
                invoice.GSTTotalAmount = invoiceDetails.TotalGST;
                if (customerID > 0)
                {
                    invoice.CustomerID = customerID;

                    POSSystem.BLL.Customers cust = new POSSystem.BLL.Customers();
                    cust.UpdateCustomerAmt(customerID, invoice.TotalAmount, invoice.PaidAmount);
                }
                invoice.IsRetail = CustomerPrice == CustomerType.CustomerPrice.SalePrice;
                invoice.InvoiceTypeID = int.Parse(ddlInvoiceType.SelectedValue);
                invoice.Deleted = false;
                invoice.InvoiceNo = txtInvoiceNo.Text;
                invoice.InvoiceCategory = (byte)Invoices.InvoiceCategories.Refund;
                invoice.Save();

                //step3:add InvoiceDetails
                InvoiceDetails ivcDetails = new InvoiceDetails();
                invoiceDetails.SaleItems.Rewind();
                for (int i = 0; i < invoiceDetails.SaleItems.RowCount; i++)
                {
                    ivcDetails.AddNew();
                    ivcDetails.BranchID = Branches.CurrentBranchID;
                    String desc = invoiceDetails.SaleItems.s_Description;
                    
                    ivcDetails.AddInfo(invoice.ID, invoiceDetails.SaleItems.ProductID, invoiceDetails.SaleItems.IMEI, invoiceDetails.SaleItems.Quantity,
                        invoiceDetails.SaleItems.GST, invoiceDetails.SaleItems.UnitPrice, invoiceDetails.SaleItems.Discount, invoiceDetails.SaleItems.Cost, desc);
                    ivcDetails.LastModifiedByUser = SessionUser.ID;
                    ivcDetails.s_ItemType = ((byte)Invoices.InvoiceCategories.Refund).ToString();
                    invoiceDetails.SaleItems.MoveNext();
                }

                ivcDetails.Save();

                if (OnFinishSubmit != null)
                    OnFinishSubmit(this, new FinishSubmitArg() { InvoiceID = invoice.ID });

                tx.CommitTransaction();

                ShowHintMessage(mainPanel, String.Format("(*) Invoice {0} has been created successfully!", txtInvoiceNo.Text));
                hidNewInvoiceID.Value = invoice.ID.ToString();
                invoiceDetails.Refresh();
                btnSubmit.Visible = false;
                btnPrint.Visible = true;

                if(chkAutoPrint.Checked)
                    PrintInvoice();
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ShowErrorMessage(mainPanel, "(*) Error: " + ex.Message);
                ErrorLog.WriteToFile("SalesCtrl.ascx.cs", "btnSubmit_OnClick", ex.StackTrace);
            }
        }

        protected void btnNewInvoice_OnClick(object sender, EventArgs e)
        {
            NewInvoice();
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return this.ResolveClientUrl("~/EditPages/PrintHandler.aspx?key=") + PrintKey;
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintInvoice();
        }

        private void PrintInvoice()
        {
            try
            {
                InvoiceViewerCtrl ivcViewer = (InvoiceViewerCtrl)LoadControl(@"~/Controls/POSControls/InvoiceViewerCtrl.ascx");
                if (hidNewInvoiceID.Value != "")
                    ivcViewer.LoadInvoiceByID(int.Parse(hidNewInvoiceID.Value));

                Session[PrintKey] = ivcViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("SalesCtrl.ascx.cs", "PrintInvoice", ex.StackTrace);
            }
        }
    }
}